package com.archerdu.commons.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.xml.sax.SAXException;

/**
 * xml工具类
 * 
 * @projectName springDemo
 * @description xml工具类
 * @author archer du
 * @createDate 2013年9月27日 下午5:21:47
 * @updateUser dxf
 * @updateDate 2013年9月27日 下午5:21:47
 * @updateRemark 新建
 * @version 0.0.1
 */
public class XMLUtil {

    // 默认文件读取编码
    private static String encoding = "utf-8";

    @SuppressWarnings("unchecked")
    public static void main(String[] args) throws IOException, DocumentException {
        Document doc = XMLUtil.get("f://t.xml", "root");
        Element root = doc.getRootElement();
        System.out.println(root.getName());
        System.out.println(root.getData());

        doc = XMLUtil.read("f://system.xml");
        @SuppressWarnings("unused")
        List<Element> list = doc.selectNodes("//entry[@key='index_title']");
    }

    /**
     * 创建XML文件并读取文件内容
     * 
     * @param name
     * @param root
     * @return
     */
    public static Document create(String name, String root) {
        Document doc = DocumentHelper.createDocument();
        doc.addElement(root);
        XMLUtil.save(name, doc);
        return doc;
    }

    /**
     * 读取XML文件内容
     * 
     * @param name
     * @return
     */
    public static Document read(String name) {
        SAXReader sr = new SAXReader();
        // doc = sr.read(config);
        Document doc = null;
        try {
            doc = sr.read(new InputStreamReader(new FileInputStream(name), XMLUtil.encoding));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return doc;
    }

    /**
     * 读取XML文件内容
     * 
     * @param name
     * @return
     * @throws SAXException
     */
    public static Document readNoDtd(String name) {
        SAXReader sr = new SAXReader();
        sr.setValidation(false);
        try {
            sr.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        } catch (SAXException e1) {
            e1.printStackTrace();
        }
        // doc = sr.read(config);
        Document doc = null;
        try {
            doc = sr.read(new InputStreamReader(new FileInputStream(name), XMLUtil.encoding));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return doc;
    }

    public static Document get(String file, String root) {
        Document doc = null;
        if (!(new File(file).exists())) {
            doc = XMLUtil.create(file, root);
        } else {
            doc = XMLUtil.read(file);
        }
        return doc;
    }

    /**
     * 保存XML文件内容，紧凑格式
     * 
     * @param source
     * @param doc
     */
    public static void save(String source, Document doc) {
        try {
            Writer w = new OutputStreamWriter(new FileOutputStream(source), XMLUtil.encoding);
            XMLWriter xw = new XMLWriter();
            xw.setWriter(w);
            xw.write(doc);
            w.close();
            xw.close();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 保存XML文件内容，紧凑格式
     * 
     * @param source
     * @param doc
     */
    public static void save(Writer w, Document doc) {
        try {
            XMLWriter xw = new XMLWriter();
            xw.setWriter(w);
            xw.write(doc);
            w.close();
            xw.close();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 保存XML文件内容为易读格式
     * 
     * @param source
     * @param doc
     */
    public static void savePretty(String source, Document doc) {
        try {
            OutputFormat of = OutputFormat.createPrettyPrint();
            Writer w = new OutputStreamWriter(new FileOutputStream(source), XMLUtil.encoding);
            XMLWriter xw = new XMLWriter(w, of);
            xw.write(doc);
            w.close();
            xw.close();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void setEncoding(String encoding) {
        XMLUtil.encoding = encoding;
    }

    public static String getEncoding() {
        return encoding;
    }
}
